const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const execSync = require('child_process').execSync;
const resReply = require('./lib/resReply').resReply;
const logger = require('./lib/logger').logger();
require('./lib/mongoose');

const app = express();
// view engine setup
//set方法用于指定变量的值，下面是指定系统变量views 和 view engine的值
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use( resReply );
// app.use( getUser );
// app.use( function( req, res, next){
//     let { StaffId, LoginName } = req.user;
//     logger.info("%d\t%s\t%s\t%s", StaffId, LoginName, req.method, req.url );
//     next();
// });

//
var stdout = execSync( 'find '+ __dirname +'/routes' );
if( stdout.toString ) stdout = stdout.toString();
stdout.split(/\n/).map( function(path){
    path = path.replace( __dirname, '.');
    var matches = path.match(/\/routes(.+?)\.js$/);
    if( matches){
        var routeName = matches[1].replace(/index$/,'');
        console.log( "load route:", routeName, path );
        app.use( routeName, require( path ) );
    }
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
    logger.error('Error: %s\t%j',req.url,err);
});

module.exports = app;
